/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.BranchDAO;
import com.cashmate.hibernate.dao.CollectionsDAO;
import com.cashmate.hibernate.dao.DccrDAO;
import com.cashmate.hibernate.pojo.Branches;
import com.cashmate.hibernate.pojo.Collections;
import com.cashmate.hibernate.pojo.Dccr;
import com.cashmate.hibernate.pojo.Employees;
import com.cashmate.utilities.ClassUtils;
import com.cashmate.utilities.DCCRDate;
import com.cashmate.utilities.Utils;
import com.opensymphony.xwork2.ActionSupport;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Dean
 */
public class ChooseDccr extends ActionSupport {

    private final Logger logger = Logger.getLogger(ChooseDccr.class);
    private String dccrdate;
    private String branch;
    private InputStream inputStream;
    private final CollectionsDAO colDao = (CollectionsDAO) ServletActionContext.getServletContext().getAttribute("collectionsDAO");
    private final Branches b = (Branches) ServletActionContext.getRequest().getSession().getAttribute("branch");
    private final DccrDAO dccrdao = (DccrDAO) ServletActionContext.getServletContext().getAttribute("dccrDAO");
    private final BranchDAO branches = (BranchDAO) ServletActionContext.getServletContext().getAttribute("branchDAO");
    private final Employees emps = (Employees) ServletActionContext.getRequest().getSession().getAttribute("employee");

    @Action(value = "/choose-dccr", results = {
        @Result(name = "success", type = "stream", params = {"inputName", "inputStream", "contentType", "text/html"})
    })
    @Override
    public String execute() throws Exception {
        try {
            if (branch == null || branch.length() < 1) {
                branch = b.getBranchid().toString();
            }
            DetachedCriteria criteria = DetachedCriteria.forClass(Collections.class);
            criteria.createCriteria("areas").createCriteria("branches", "b").setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
            DCCRDate date = new DCCRDate(Utils.stringArrToDateTime(dccrdate.split("/")));
            Disjunction disjunc = Restrictions.disjunction();
            disjunc.add(Restrictions.eq("date", dccrdate));
            for (String s : date.getPastDaysAfterCutOff()) {
                disjunc.add(Restrictions.eq("date", s));
            }
            criteria.add(disjunc);
            if (branch == null || branch.length() < 1) {
                criteria.add(Restrictions.eq("b.branchid", b.getBranchid()));
            } else {
                criteria.add(Restrictions.eq("b.branchid", Integer.parseInt(branch)));
            }
            int record = colDao.countByCriteria(criteria);
            criteria.setProjection(null);
            criteria.setResultTransformer(Criteria.ROOT_ENTITY);
            logger.debug(ClassUtils.toString(this));
            if (record < 1) {
                inputStream = new StringBufferInputStream("<script type=\"text/javascript\">"
                        + "$('div#formResult').removeClass(\"ui-state-highlight\");"
                        + "$('div#formResult').addClass(\"ui-state-error\");"
                        + "$('div#formResult').html(error(\"There is no payment made in " + dccrdate + " for this branch.\"));"
                        + "$('#indicator').hide();"
                        + "$('#chooseDCCRForm').fadeIn();"
                        + "$('.dialogbutton').fadeIn();"
                        + "</script>");
                return SUCCESS;
            } else {
                ServletActionContext.getRequest().getSession().setAttribute("dccrdate", dccrdate);
                ServletActionContext.getRequest().getSession().setAttribute("dccrbranch", branch);
                DetachedCriteria criteria2 = DetachedCriteria.forClass(Dccr.class);
                criteria2.add(Restrictions.eq("dategenerated", dccrdate));
                criteria2.add(Restrictions.eq("branchid", Integer.parseInt(branch)));
                criteria2.add(Restrictions.eq("isactive", true));
                int record2 = dccrdao.countByCriteria(criteria2);
                criteria2.setProjection(null);
                criteria2.setResultTransformer(Criteria.ROOT_ENTITY);
                if (record2 > 0) {
                    inputStream = new StringBufferInputStream("<script type=\"text/javascript\">"
                            + "$('div#formResult').removeClass(\"ui-state-highlight\");"
                            + "$('div#formResult').addClass(\"ui-state-error\");"
                            + "$('div#formResult').html(error(\"A D.C.C.R already exists in this date (" + dccrdate + ").\"));"
                            //+ "$('#confirmGen').fadeIn();" Uncomment to allow overwriting existing DCCR.
                            + "$('#indicator').hide();"
                            + "$('#chooseDCCRForm').fadeIn();"
                            + "$('.dialogbutton').fadeIn();"
                            + "</script>");
                    return SUCCESS;
                }
            }
            dccrProc();
            ServletActionContext.getRequest().getSession().setAttribute("dccrgendate", date);
            ServletActionContext.getRequest().getSession().setAttribute("dccrbranchname", branches.get(Integer.parseInt(branch)).getBranchname());
            inputStream = new StringBufferInputStream("<script type=\"text/javascript\">firewarn=false;window.location=\"dccr.jsp\";</script>");
        } catch (Exception e) {
            //catch whichever exception, get the current session info of the employee and log it.

            if (emps != null) {
                logger.fatal("(" + emps.getIdnumber() + "):" + e.getLocalizedMessage(), e);
            } else {
                logger.fatal(e.getLocalizedMessage(), e);
            }
            e.printStackTrace();
            //add action errors this will correspond to <s:actionerror/> in a struts-enabled jsp page.
            addActionError(e.getLocalizedMessage());

            //if error then chain result to messages.jsp, which will display errors/messages.
            return ERROR;
        } finally {
            CollectionsDAO.close();
            DccrDAO.close();
        }
        return SUCCESS;
    }

    private void dccrProc() throws Exception {
        dccrdao.dccrProcedure(dccrdate, Integer.parseInt(branch));
        logger.info("Employee " + emps.getIdnumber() + " generated DCCR for " + dccrdate + " at "
                + branches.get(Integer.parseInt(branch)).getBranchname());
    }

    public void setDccrdate(String dccrdate) {
        this.dccrdate = dccrdate;
    }

    public void setBranch(String branch) {
        this.branch = branch;
    }

    public String getBranch() {
        return branch;
    }

    public String getDccrdate() {
        return dccrdate;
    }

    public InputStream getInputStream() {
        return inputStream;
    }
    /*
     * dccrProcedure gets executed twice... i dunno why.
     * set restrictions in stored procedure
     * query 
     */
}
